package com.tfj.mvp.base;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Looper;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentTransaction;
import androidx.appcompat.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.hyphenate.tfj.R;
import com.tfj.mvp.tfj.detail.VDetailActivity;
import com.tfj.mvp.tfj.per.logreg.VLogActivity;
import com.hitomi.tilibrary.transfer.Transferee;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.tfj.comm.bean.Constant;
import com.tfj.utils.AlertUtils;
import com.tfj.utils.PermissionUtils;
import com.tfj.utils.StatusBarUtil;

import butterknife.ButterKnife;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;


/**
 * Created by HQ on 2017/9/29.
 * Fragment基类
 */

public abstract class BaseFragment<T extends BasePresenter> extends BaseTFragment {
    private AlertDialog loading;
    private int height_statusbar = 0;
    public String TAG =  this.getClass().getSimpleName();
    private LinearLayout linearlayout_status;
    protected View findViewById(int id) {
        return getView().findViewById(id);
    }
    public boolean ifNeedStatus = true;
    private Toast mToast;
    public CompositeDisposable mCompositeDisposable;
    protected Context mContext;
    public View mRootView;
    public T mPresenter;
    protected Transferee transferee;
    protected DisplayImageOptions options;
    private String STATE_SAVE_IS_HIDDEN = "dasdasdasd";

    /**
     * 获得全局的，防止使用getActivity()为空
     *
     * @param context
     */
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mContext = context;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            boolean isSupportHidden = savedInstanceState.getBoolean(STATE_SAVE_IS_HIDDEN);

            FragmentTransaction ft = getFragmentManager().beginTransaction();
            if (isSupportHidden) {
                ft.hide(this);
            } else {
                ft.show(this);
            }
            ft.commit();
        }
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean(STATE_SAVE_IS_HIDDEN, isHidden());
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
            savedInstanceState) {

        if (mRootView == null) {
            if (getLayoutRes() != 0) {
                mRootView = LayoutInflater.from(mContext)
                        .inflate(getLayoutRes(), container, false);
                ButterKnife.bind(this, mRootView);
                mCompositeDisposable = new CompositeDisposable();
                createPresenter();
                initView();
                initTrans();
            } else {
                throw new RuntimeException("layoutResID==-1 have u create your layout?");
            }
        }

        return mRootView;
    }
    public  void initTrans(){
        options = new DisplayImageOptions
                .Builder()
                .showImageOnLoading(R.mipmap.ic_launcher)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .resetViewBeforeLoading(true)
                .build();
        transferee = Transferee.getDefault(getActivity());
        ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(getActivity()));
    }
    /**
     * 添加订阅
     */
    public void addDisposable(Disposable mDisposable) {
        if (mCompositeDisposable == null) {
            mCompositeDisposable = new CompositeDisposable();
        }
        mCompositeDisposable.add(mDisposable);
    }

    /**
     * 取消所有订阅
     */
    public void clearDisposable() {
        if (mCompositeDisposable != null) {
            mCompositeDisposable.clear();
        }
    }
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        StatusBarUtil.StatusBarLightMode(getActivity());
        if(ifNeedStatus){
            int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0) {
                height_statusbar = getResources().getDimensionPixelSize(resourceId);
            }
            linearlayout_status = (LinearLayout) findViewById(R.id.linearlayout_status);
            if(linearlayout_status!=null){
                ViewGroup.LayoutParams paras = linearlayout_status.getLayoutParams();
                paras.height = height_statusbar;
                linearlayout_status.setLayoutParams(paras);
            }
        }
    }
    public void LoadImageUrlRound (ImageView id, String imageurl,int angle){

        RoundedCorners roundedCorners= new RoundedCorners(angle);
        RequestOptions options = RequestOptions.bitmapTransform(roundedCorners).override(300, 300);
        options.placeholder(R.mipmap.ic_launcher);
        options.error(R.mipmap.ic_launcher);
        options.diskCacheStrategy(DiskCacheStrategy.RESOURCE);
        options.dontAnimate();
        Glide.with(mContext).load(imageurl).apply(options).thumbnail(Constant.THUMB_PER).into(id);
    }
    public void LoadImageUrl (ImageView id, String imageurl){
        RequestOptions options = new RequestOptions();
        options.placeholder(R.mipmap.ic_launcher);
        options.error(R.mipmap.ic_launcher);
        options.diskCacheStrategy(DiskCacheStrategy.RESOURCE);
        options.dontAnimate();
        Glide.with(mContext).load(imageurl).apply(options).thumbnail(Constant.THUMB_PER).into(id);
    }
//    public void LoadFresco(SimpleDraweeView placeHolderImageDraweeView,String url ,boolean ifRound){
//        GenericDraweeHierarchy hierarchy =   GenericDraweeHierarchyBuilder.newInstance(getResources())
//                                                  .setRoundingParams(ifRound?RoundingParams.asCircle():RoundingParams.fromCornersRadius(0f))
//                                                  .build();
//        /**
//         * 设置淡入淡出效果的显示时间
//         * */
//        hierarchy.setPlaceholderImage(R.mipmap.ic_launcher);
//        hierarchy.setFailureImage(getResources().getDrawable(R.drawable.dianzan_check));
//        DraweeController placeHolderDraweeController = Fresco.newDraweeControllerBuilder()
//                .setUri(url) //为图片设置url
//                .setTapToRetryEnabled(true)   //设置在加载失败后,能否重试
//                .setOldController(placeHolderImageDraweeView.getController())
//                .build();
//        placeHolderImageDraweeView.setController(placeHolderDraweeController);
//        placeHolderImageDraweeView.setHierarchy(hierarchy);
//    }
    protected void showToast(final String text) {
        if (mToast == null) {
            mToast = Toast.makeText(getActivity(), text, Toast.LENGTH_LONG);
        }
        if (Thread.currentThread() != Looper.getMainLooper().getThread()) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mToast.setText(text);
                    mToast.show();
                }
            });
        } else {
            mToast.setText(text);
            mToast.show();
        }
    }
    /**
     * 显示前往应用设置Dialog
     */
    public void toSetting() {
        new AlertDialog.Builder(getActivity())
                .setTitle("需要权限")
                .setMessage("我们需要相关权限，才能实现功能，点击前往，将转到应用的设置界面，请开启应用的相关权限。")
                .setPositiveButton("前往", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        PermissionUtils.toAppSetting(getActivity());
                    }
                })
                .setNegativeButton("取消", null).show();
    }

    public void loadingView(boolean isLoading,String content) {
        if (isLoading) {
            if (loading == null) {
                loading = AlertUtils.loadingDialog(getActivity(),content);
            }
            if (!loading.isShowing()) {
                loading.show();
                getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);

            }
        } else {
            if (loading != null && loading.isShowing()) {
                loading.dismiss();
                getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
            }
        }
    }
    /**
     * 创建presenter实例
     */
    public abstract void createPresenter();

    public void toWeb(String url){
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);
    }
    /**
     * 初始化
     */
    protected abstract void initView();



    /**
     * activity跳转（无参数）
     *
     * @param className
     */

    public void startActivity(Class<?> className) {
        Intent intent = new Intent(mContext, className);
        startActivity(intent);
    }

    /**
     * activity跳转（有参数）
     *
     * @param className
     */
    public void startActivity(Class<?> className, Bundle bundle) {
        Intent intent = new Intent(mContext, className);
        intent.putExtras(bundle);
        startActivity(intent);
    }
    public void toDetail(String id){
        Intent intent = new Intent (getActivity(), VDetailActivity.class);
        intent.putExtra("id",id);
        startActivity(intent);
    }
    public void toLogin(){
        startActivity(VLogActivity.class);
    }
    /**
     * 传入布局文件
     *
     * @return
     */
    public abstract int getLayoutRes();

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.onDestroy();//页面销毁网络请求也取消
        }
        ButterKnife.bind(getActivity()).unbind();
        clearDisposable();
    }
    public void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive() && getActivity().getCurrentFocus() != null) {
            if (getActivity().getCurrentFocus().getWindowToken() != null) {
                imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }
}
